package com.th.apicenter.cainiao;


import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 报文加密类
 */
public class EncryptUtil {

    public static String DoSign(String content, String charset, String appSecret) {
        try {
            String toSignContent = content + appSecret;

            // 获取指定字符集的字节数组
            Charset encoding = Charset.forName(charset);
            byte[] inputBytes = toSignContent.getBytes(encoding);

            // 计算MD5哈希
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md5.digest(inputBytes);

            // Base64编码
            return Base64.getEncoder().encodeToString(hashBytes);
        } catch (NoSuchAlgorithmException e) {
            // 正常情况下不会触发，因为MD5是Java标准算法
            throw new RuntimeException("MD5 algorithm not available", e);
        } catch (IllegalArgumentException e) {
            // 处理不支持的字符集异常
            throw new IllegalArgumentException("Unsupported charset: " + charset, e);
        }
    }

}